package com.ljl.module.common.config;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 日志切面管理器
 *
 * @author ljl
 */
@Aspect
@Component
public class MyLogHandler {
    /**
     * 日志记录器
     */
    private static final Logger logger = LogManager.getLogger(MyLogHandler.class);

    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.ljl.module.common.annotation.MyLog)")
    public void pointCut() {
        // 不用做什么，这里只是声明了一个切点，在程序中不会实际运行
    }

    /**
     * aop日志处理
     *
     * @param joinPoint 切面
     * @return 返回值
     */
    @Around(value = "pointCut()", argNames = "joinPoint")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        if (signature instanceof MethodSignature) {
            MethodSignature methodSignature = (MethodSignature) signature;
            logger.info("point:{},params:{}", methodSignature.getDeclaringTypeName() + "." + methodSignature.getName(), joinPoint.getArgs());
            Object proceed = joinPoint.proceed();
            logger.info("point:{},result:{}", methodSignature.getDeclaringTypeName() + "." + methodSignature.getName(), proceed);
            return proceed;
        } else {
            return joinPoint.proceed();
        }
    }

    /**
     * 异常处理
     *
     * @param throwable 异常
     */
    @AfterThrowing(pointcut = "pointCut()", throwing = "throwable")
    public void exceptionHandler(Throwable throwable) {
        logger.error("exception:{}", throwable.getMessage());
    }
}
